package com.acme.bankapp.domain.bank.accounts;

import com.acme.bankapp.exceptions.NotEnoughFundsException;
import com.acme.bankapp.exceptions.OverDraftLimitExceededException;

public class CheckingAccount extends AbstractAccount {

	private double overdraft;

	public CheckingAccount(double amount, double overdraft) {
		super(amount);
		this.overdraft = overdraft;
	}

	public double getOverdraft() {
		return overdraft;
	}


	@Override
	public void deposit(double amount) {
		setBalance(getBalance() + amount);
	}

	@Override
	public void withdraw(double amount) throws OverDraftLimitExceededException {
		try {
			super.withdraw(amount);
		} catch (NotEnoughFundsException e) {
			if (e.getAmount() > overdraft) {
				throw new OverDraftLimitExceededException(e.getAmount() - overdraft, this);
			}
			setBalance(0);
			overdraft -= e.getAmount();
		}

		assert overdraft >= 0 : "Negative overdraft";
	}

	@Override
	public double maximumAmountToWithdraw() {
		return getBalance() + overdraft;
	}

	@Override
	public boolean equals(Object o) {
		if (!super.equals(o)) return false;

		CheckingAccount that = (CheckingAccount) o;

		if (Double.compare(that.overdraft, overdraft) != 0) return false;

		return true;
	}

	@Override
	public int hashCode() {
		int result = super.hashCode();
		long temp;
		temp = Double.doubleToLongBits(overdraft);
		result = 31 * result + (int) (temp ^ (temp >>> 32));
		return result;
	}

	@Override
	public String toString() {
		return super.toString() + " overdraft=" + overdraft;
	}
}
